const express = require('express');
const router = express.Router();

const Connection = require('../models/Connection'); // 导入Connection模型

// 获取所有连接
router.get('/', async (req, res) => {
  try {
    const { tabId } = req.query;
    const query = tabId ? { tabId } : {};
    const connections = await Connection.find(query);
    res.json({ code: 0, data: connections });
  } catch (error) {
    res.status(500).json({ code: -1, message: '服务器错误', error: error.message });
  }
});

// 创建新连接
router.post('/', async (req, res) => {
  try {
    const { from, to, fromSide, toSide, tabId } = req.body;

    if (!from || !to || !fromSide || !toSide || !tabId) {
      return res.status(400).json({ code: -1, message: '源卡片ID、目标卡片ID、源侧边、目标侧边和标签ID是必需的' });
    }

    // 验证侧边值
    const validSides = ['top', 'right', 'bottom', 'left'];
    if (!validSides.includes(fromSide) || !validSides.includes(toSide)) {
      return res.status(400).json({ code: -1, message: '侧边值必须是 top、right、bottom 或 left 之一' });
    }

    const newConnection = new Connection({
      id: Date.now().toString(), // 使用时间戳作为唯一ID
      from,
      to,
      fromSide,
      toSide,
      tabId,
    });

    await newConnection.save();
    res.status(201).json({ code: 0, data: newConnection });
  } catch (error) {
    res.status(400).json({ code: -1, message: '创建连接失败', error: error.message });
  }
});

// 删除连接
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const connection = await Connection.findOneAndDelete({ id });

    if (!connection) {
      return res.status(404).json({ code: -1, message: '找不到连接' });
    }

    res.json({ code: 0, message: '连接删除成功' });
  } catch (error) {
    res.status(500).json({ code: -1, message: '删除连接失败', error: error.message });
  }
});

// 删除多个
router.delete('/', async (req, res) => {
  try {
    const { ids } = req.body;
    if (!ids || !Array.isArray(ids)) {
      return res.status(400).json({ code: -1, message: 'ids 是必需的数组' });
    }
    await Connection.deleteMany({ id: { $in: ids } });
    res.json({ code: 0, message: '连接删除成功' });
  } catch (error) {
    res.status(500).json({ code: -1, message: '删除连接失败', error: error.message });
  }
});

module.exports = router;